<template>
  <div class="container">
    <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="auto" class="demo-ruleForm">
      <el-form-item label="用户名" prop="name">
        <el-input v-model="ruleForm.name" class="input" />
      </el-form-item>

      <el-form-item label="密 码" prop="pass">
        <el-input v-model="ruleForm.pass" type="password" autocomplete="off" class="input" />
      </el-form-item>

      <el-form-item class="button">
        <el-button type="primary" plain @click="submitForm(ruleFormRef)">登 录</el-button>
        <el-button @click="resetForm(ruleFormRef)">清 空</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { postLogin } from '../request'
import { useRouter } from 'vue-router'
import { ElNotification } from 'element-plus'

const router = useRouter()

const ruleFormRef = ref()

// 用户名校验规则
const checkName = (_rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('Please input the name'))
  }
  const temp = /\w{6,18}/
  if (temp.test(value)) {
    callback()
  } else {
    callback(new Error('Please input 6-18 characters'))
    callback()
  }
}
// 密码校验规则
const validatePass = (_rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('Please input the password'))
  } else {
    callback()
  }
}

// 表单数据
const ruleForm = reactive({
  pass: '',
  name: '',
})

// 校验规则
const rules = reactive({
  pass: [{ validator: validatePass, trigger: 'blur' }],
  name: [{ validator: checkName, trigger: 'blur' }],
})

// 提交表单
const submitForm = (formEl: any) => {
  if (!formEl) return
  formEl.validate((valid: any) => {
    if (valid) {
      console.log('submit!')
      postLogin(ruleForm.name, ruleForm.pass)
        .then((res) => {
          console.log(res)
          // 登录成功将获取的token存到本地
          window.sessionStorage.setItem("token", res.data.token)
          ElNotification({
            title: '登录成功',
            message: '快去发送消息吧！',
            type: 'success',
            duration: 1000
          })
          // 跳转到发送消息界面
          router.push('/user')
        })
        .catch((err) => {
          console.log(err);
        });
    }
  })
}

// 重置表单
const resetForm = (formEl: any) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style scoped>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 320px;
  height: 200px;
  margin: 200px auto 0;
  background-color: rgb(248, 250, 239);
  border-radius: 10px;
  box-shadow: 0px 0px 50px 30px rgb(96, 94, 94);
  opacity: .85;
}

.input {
  width: 200px;
}

.button {
  position: relative;
  left: 66px;
}
</style>